<!--
 * @Description  :
 * @Autor        : guoxi
 * @Date         : 2022-06-29 14:08:57
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2022-08-05 14:07:44
 * @FilePath     : \rpms\src\views\document\scientific\award\index.vue
-->
<template>
  <div class="content">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header content="科技奖励" @back="goback"></el-page-header>
        <div class="card-box--setbtn" v-if="isEdit">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box form-box">
      <el-form
        :disabled="!isEdit"
        :model="model.formData"
        ref="formRef"
        @submit.prevent
        :rules="model.formRules"
        label-width="160px"
      >
        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="成果来源" prop="paperType">
              <el-select
                style="width: 100%"
                v-model="model.formData.paperType"
                clearable
                placeholder="请选择"
                value-key="id"
              >
                <el-option
                  v-for="(item, index) in model.paperTypes"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="获奖项目" prop="rewardProject">
              <el-input v-model.trim="model.formData.rewardProject"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="model.formData.paperType === '1'">
          <el-col :xl="8" :lg="12">
            <el-form-item label="所属项目" placeholder="请选择所属项目">
              <el-select
                style="width: 100%"
                v-model="model.formData.projectId"
                clearable
                placeholder="请选择"
                value-key="id"
                @change="handleSelected"
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="项目编号" prop="projectNum">
              <el-input
                disabled
                v-model.trim="model.formData.projectNum"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="奖项类别" prop="rewardsType">
              <el-select
                v-model="model.formData.rewardsType"
                clearable
                style="width: 100%"
                value-key="dicCode"
              >
                <el-option
                  v-for="item in model.rewardsTypes"
                  :key="item.key"
                  :label="item.label"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="奖励级别" prop="rewardsLevel">
              <el-select
                v-model="model.formData.rewardsLevel"
                clearable
                style="width: 100%"
                value-key="dicCode"
              >
                <el-option
                  v-for="item in model.rewardsLevels"
                  :key="item.key"
                  :label="item.label"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="获奖时间" prop="awardsYear">
              <el-date-picker
                style="width: 100%"
                v-model="model.formData.awardsYear"
                value-format="YYYY"
                type="year"
              />
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="所属公司主体" prop="principalCompanyCode">
              <el-select
                v-model="model.formData.principalCompanyCode"
                clearable
                style="width: 100%"
                value-key="dicCode"
              >
                <el-option
                  id="default-option"
                  v-for="item in principalCompanyArr"
                  :key="item.dicCode"
                  :label="item.dicValue"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="颁奖单位" prop="grantAwardsDept">
              <el-input
                v-model.trim="model.formData.grantAwardsDept"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="项目牵头单位名称" prop="leadDept">
              <el-input v-model.trim="model.formData.leadDept"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xl="16" :lg="24">
            <el-form-item label="获奖单位" prop="publishDepts">
              <el-select
                popper-class="dept"
                style="width: 100%"
                v-model="model.formData.publishDepts"
                placeholder="请选择"
                clearable
                multiple
                @remove-tag="handleRemovePartake"
              >
                <!-- :label="formData.projectUnderUnit" -->
                <el-option :value="joinDeptList">
                  <el-tree
                    show-checkbox
                    :data="joinDeptList"
                    node-key="id"
                    ref="deptTreePartakeRef"
                    :props="defaultProps"
                    @check-change="handleCheckChangePartake"
                    check-on-click-node
                    check-strictly
                    :expand-on-click-node="false"
                  ></el-tree>
                </el-option>
              </el-select>
              <el-table
                v-if="model.formData.partakeUnit.length > 0"
                :data="model.formData.partakeUnit"
                border
                :header-cell-style="{
                  background: '#eef1f6',
                  color: '#606266'
                }"
              >
                <template #empty>
                  <el-empty :image-size="40" description="暂无数据"></el-empty>
                </template>

                <el-table-column
                  prop="partakeUnitName"
                  label="单位名称"
                ></el-table-column>
                <el-table-column
                  prop="partakeUnitCode"
                  label="单位编号"
                ></el-table-column>

                <el-table-column label="单位类型">
                  <template #default="scope">
                    {{ scope.row.isEmp ? "外部单位" : "内部单位" }}
                  </template>
                </el-table-column>
                <el-table-column label="项目排名">
                  <template #default="scope">
                    <el-select
                      class="w40"
                      value-key="key"
                      v-model="scope.row.rank"
                    >
                      <el-option
                        v-for="item in model.authorRanks"
                        :key="item.key"
                        :label="item.label"
                        :value="item.key"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="上传文档" prop="attachment">
              <ecm-upload
                :files="defaultFileList"
                :docid="model.docid"
                @setFile="handleSuccess"
              ></ecm-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col>
            <el-form-item label="上传文档" prop="attachment">
              <el-upload
                name="uploadFile"
                multiple
                :accept="acceptTypes"
                :action="uploadComUrl"
                :headers="uploadHeaders"
                :on-success="handleSuccess"
                :on-remove="handleRemove"
                :on-error="handleError"
                :file-list="defaultFileList"
                :before-upload="beforeAvatarUpload"
                :on-preview="handlePreview"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
    </el-card>
    <approval ref="approvalRef"></approval>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { postDeptList } from "/@/api/dept";
import { addRewards, updateRewards, getRewardsById } from "/@/api/document";
import { postSysCompanyList } from "/@/api/organization";
import { postProjectList } from "/@/api/project";
import NotifMessage from "/@/utils/message/notification";
import { postDictList } from "/@/api/common";
import EcmUpload from "/@/components/ecmUpload/index.vue";
import Approval from "../approval.vue";
const approvalRef = ref<HTMLFormElement | null>(null) as any;
const router = useRouter();
const route = useRoute();
let model = reactive({
  docid: window["ecmDocType"].award,
  mode: "Add",
  dialogFormVisible: false,
  data: [],
  loading: false,
  paperTypes: [
    { name: "项目", value: "1" },
    { name: "非项目", value: "2" }
  ],
  authorRanks: [
    { key: "1", label: "一" },
    { key: "2", label: "二" },
    { key: "3", label: "三" },
    { key: "4", label: "其它" }
  ],
  rewardsLevels: [
    { key: "0", label: "特等奖" },
    { key: "1", label: "一等奖" },
    { key: "2", label: "二等奖" },
    { key: "3", label: "其他" },
    { key: "4", label: "不分等级" }
  ],
  rewardsTypes: [
    { key: "1", label: "国家最高科学技术奖" },
    { key: "2", label: "国家自然科学奖" },
    { key: "3", label: "国家技术发明奖" },
    { key: "4", label: "国家科学技术进步奖" },
    { key: "5", label: "国际科学技术合作奖" },
    { key: "6", label: "省部级科技奖" },
    { key: "7", label: "其他科技奖" }
  ],
  firstAwardss: [
    { key: "1", label: "是" },
    { key: "0", label: "否" }
  ],
  formData: {
    principalCompanyCode: null,
    paperType: "",
    projectNum: "",
    projectName:"",
    projectId: null,
    rdScientificId: null,
    rewardsType: null,
    rewardsLevel: null,
    grantAwardsDept: null,
    leadDept: null,
    awardsYear: null,
    rewardProject: "",
    attachment: [],
    partakeUnit: [],
    publishDepts: []
  },
  formRules: {
    rewardProject: [
      { required: true, message: "请输入获奖项目", trigger: "change" }
    ],
    rewardsType: [
      { required: true, message: "请选择奖项类别", trigger: "change" }
    ],
    rewardsLevel: [
      { required: true, message: "请选择奖励级别", trigger: "change" }
    ],
    publishDepts: [
      { required: true, message: "请输入获奖单位", trigger: "change" }
    ],
    grantAwardsDept: [
      { required: true, message: "请输入颁奖单位", trigger: "change" }
    ],

    leadDept: [
      { required: true, message: "请输入牵头单位名称", trigger: "change" }
    ],

    awardsYear: [
      { required: true, message: "请选择发表时间", trigger: "change" }
    ],
    principalCompanyCode: [
      { required: true, message: "请选择所属公司主体", trigger: "change" }
    ],
    attachment: [{ required: true, message: "请上传附件", trigger: "change" }]
  }
});

const formRef = ref<HTMLFormElement | null>(null) as any;
const deptTreePartakeRef = ref<HTMLElement | null>(null) as any;
let joinDeptList = ref([]);
let principalCompanyArr = ref([]);

const initPrincipalCompanyList = async () => {
  try {
    const params = {
      dicType: "rd_principal_cmpy"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      principalCompanyArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

const defaultProps = {
  children: "children",
  label: "deptDescShrt",
  id: "id"
};
let projectList = ref([]);
let defaultFileList = ref([]);

const goback = () => {
  router.push("/document/scientific?activeName=6");
};

const handleSelected = item => {
  const target = projectList.value.find(el => el.id === item);
  model.formData.projectNum = target.projectCode;
  model.formData.projectName = target.projectName;
};

// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectList({ pageNum: 1, pageSize: 0 });
    if (code === 200) {
      projectList.value = data.list;
      model.formData.projectNum = data.list.find(
        el => el.id === model.formData.projectId
      )?.projectCode;
    }
  } catch (err) {
    console.log(err);
  }
};

const handleSuccess = res => {
  defaultFileList.value = res.file;
  model.formData.attachment = res.file;
  formRef.value.clearValidate();
};

const handleRemovePartake = event => {
  model.formData.partakeUnit = model.formData.partakeUnit.filter(item => {
    if (item.partakeUnitName !== event) {
      return item;
    }
  });
  deptTreePartakeRef.value.setCheckedKeys(
    model.formData.partakeUnit.map(item => {
      return item.partakeUnitCode;
    })
  );
};

const handleCheckChangePartake = (
  checkedNodes,
  checkedKeys,
  halfCheckedNodes,
  halfCheckedKeys
) => {
  console.log(checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys);
  const res = deptTreePartakeRef.value.getCheckedNodes();
  const newData =
    res.length &&
    res.map(item => {
      return {
        partakeUnitCode: item.id,
        partakeUnitName: item.deptDescShrt,
        isEmp: item.isEmp,
        rank: item.rank || "1"
      };
    });
  if (res.length) {
    model.formData.partakeUnit = newData;
    model.formData.publishDepts = newData.map(el => el.partakeUnitName);
  } else {
    model.formData.partakeUnit = [];
    model.formData.publishDepts = [];
  }
};

const handleSubmit = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  try {
    const params = JSON.parse(JSON.stringify(model.formData));
    params.attachment = JSON.stringify(params.attachment);
    params["deptList"] = params.partakeUnit.map(el => {
      return {
        refCode: el.partakeUnitCode,
        bizName: el.partakeUnitName,
        bizRank: el.rank,
        bizType: "2",
        scientificType: "5"
      };
    });
    delete params.partakeUnit;
    delete params.publishDepts;
    if (model.formData.paperType === "2") {
      params.projectId = null;
      params.projectNum = null;
    }
    if (+params.principalCompanyCode.dicCode > 2) {
      params["companyEntityCode"] = params.principalCompanyCode.dicCode;
      params["companyEntityName"] = params.principalCompanyCode.dicValue;
      params["companyEntityMaxCode"] = "3";
      params["companyEntityMaxName"] = "华润酒业";
    } else {
      params["companyEntityCode"] = params.principalCompanyCode.dicCode;
      params["companyEntityName"] = params.principalCompanyCode.dicValue;
      params["companyEntityMaxCode"] = params.principalCompanyCode.dicCode;
      params["companyEntityMaxName"] = params.principalCompanyCode.dicValue;
    }
    if (+params.principalCompanyCode.dicCode === 1) {
      params["companyEntityMaxName"] = "华润啤酒";
    }
    if (model.mode === "Add") {
      const { code, message,data } = await addRewards(params);
      if (code === 200) {
        const businessId = data;
        model.formData.name = model.formData.rewardProject;
        approvalRef.value.handleSubmit(businessId,model.formData,55);
      } else {
        NotifMessage.error(message);
      }
    } else {
      const { code, message } = await updateRewards(params);
      if (code === 200) {
        if(source && source === "back"){//驳回到第一步
          approvalRef.value.approvalSubmit(55);
        }
        else{//审批完之后，重新发起
          const businessId = route.query.rdScientificId;
          model.formData.name = model.formData.rewardProject;
          approvalRef.value.handleSubmit(businessId,model.formData,55);
        }
      } else {
        NotifMessage.error(message);
      }
    }
  } catch (e) {
    model.dialogFormVisible = false;
  }
  model.dialogFormVisible = false;
};

const initDeptList = async () => {
  const { code, data } = await postDeptList({
    pageSize: 0
  });
  let deptList = [];
  if (code === 200) {
    deptList = data.map(item => {
      return {
        id: item.id,
        deptDescShrt: item.deptDescShrt,
        children: item.children
      };
    });
  }
  let companyList = [];
  const res = await postSysCompanyList({
    pageSize: 0
  });
  if (res.code === 200) {
    res.data.list.map(el => {
      companyList.push({
        id: el.id,
        deptDescShrt: el.companyName,
        isEmp: true
      });
    });
  }

  joinDeptList.value = [
    {
      deptDescShrt: "内部单位",
      disabled: true,
      children: deptList,
      id: "0-0"
    },
    {
      deptDescShrt: "外部单位",
      disabled: true,
      children: companyList,
      id: "0-1"
    }
  ];
};

const getData = async id => {
  defaultFileList.value = [];
  const { data } = await getRewardsById(id);
  data["publishDepts"] = [];
  data["partakeUnit"] = data.deptList.map(item => {
    data["publishDepts"].push(item.bizName);
    return {
      partakeUnitCode: item.refCode,
      partakeUnitName: item.bizName,
      isEmp: item.isEmp,
      rank: item.bizRank + ""
    };
  });

  model.formData = data;
  model.formData.principalCompanyCode = {
    dicCode: data.companyEntityCode,
    dicValue: data.companyEntityName
  };
  model.formData.attachment = JSON.parse(model.formData.attachment as any);
  defaultFileList.value = model.formData.attachment;
  defaultFileList.value.map(el => {
    el["name"] = el.fileName;
  });
  model.formData.paperType = data.projectId ? "1" : "2";
  // model.formData.projectNum = route.query.projectNum as any;
};
const source = route.query.source;   //驳回到第一步，然后待办里面点击可以重新调到该页面，重新走流程审批
const isEdit = route.query.mode === "edit" ? true : false;
const id = route.query.id;
if (id) {
  model.mode = "Edit";
  getData(id);
}
getProjectList();
initDeptList();
initPrincipalCompanyList();
</script>

<style lang="scss" scoped>
.content {
  .card-box--headerwrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .card-box--setbtn {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 140px;
  }
}
</style>
